package com.supor.aiot.common.app.api;

import com.android.baseconfig.base.BaseRetrofit;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;

import io.reactivex.rxjava3.core.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: FileUploadImpl <br>
 * 作者: lei <br>
 * 日期: 2021/1/11 <br>
 */
public class FileUploadImpl extends BaseRetrofit<FileUploadService> implements FileUploadService {
    private static FileUploadImpl instance;

    public static FileUploadImpl getInstance() {
        if (instance == null) {
            instance = new FileUploadImpl();
        }
        return instance;
    }

    /**
     * 多文件上传
     *
     * @param key MultipartBody.Part key
     * @param files files
     * @return
     */
    public Observable<String> uploadFiles(String key, List<File> files) {
        List<MultipartBody.Part> parts = filesToMultipartBodyParts(key, files);
        return uploadFilesWithParts(parts);
    }

    private List<MultipartBody.Part> filesToMultipartBodyParts(@NonNull String key, @NonNull List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (int i = 0; i < files.size(); i++) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(i));
            MultipartBody.Part part = MultipartBody.Part.createFormData((key + (i + 1)), files.get(i).getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }

    @Override
    public Observable<String> uploadFilesWithParts(List<MultipartBody.Part> parts) {
        return api.uploadFilesWithParts(parts).compose(this.applySchedulers());
    }
}
